package com.soujiayi.activity;

import java.util.Stack;

import com.soujiayi.store.SPResolver;
import com.soujiayi.util.Constants;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;

public class MyApplication extends Application {

	private String sessionId = "";
	private Stack<Activity> activities = new Stack<Activity>();
	private boolean updateShown = false;

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		// 异常处理，不需要处理时注释掉这两句即可！
		CrashHandler crashHandler = CrashHandler.getInstance();
		crashHandler.init(this.getApplicationContext());
		initSessionId();

	}

	public boolean isUpdateShown() {
		return updateShown;
	}

	public void setUpdateShown(boolean updateShown) {
		this.updateShown = updateShown;
	}

	public String getSessionId() {
		return sessionId;
	}

	public void setSessionId(String sessionId) {
		this.sessionId = sessionId;
	}

	public void initSessionId() {
		SPResolver spr = new SPResolver(this, Constants.SP_SYSTEM,
				Context.MODE_PRIVATE);
		spr.OpenEditor();
		this.sessionId = spr.getValue(Constants.SP_SESSION_ID, "");
		spr.closeEditor();
	}

	public void addActivity(Activity activity) {
		activities.add(activity);
	}

	public void exit() {
		ActivityManager activityMgr = (ActivityManager) this
				.getSystemService(Context.ACTIVITY_SERVICE);
		try {
			for (Activity activity : activities) {
				if (activity != null && !activity.isFinishing()) {
					activity.finish();
				}
			}
			activities.clear();

			int currentVersion = android.os.Build.VERSION.SDK_INT;
			if (currentVersion > android.os.Build.VERSION_CODES.ECLAIR_MR1) {
				Intent startMain = new Intent(Intent.ACTION_MAIN);
				startMain.addCategory(Intent.CATEGORY_HOME);
				startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(startMain);
				System.exit(0);
			} else {// android2.1
				ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
				am.restartPackage(getPackageName());
			}
		} catch (Exception e) {
			System.out.println("exception");
			e.printStackTrace();

			int currentVersion = android.os.Build.VERSION.SDK_INT;
			if (currentVersion > android.os.Build.VERSION_CODES.ECLAIR_MR1) {
				Intent startMain = new Intent(Intent.ACTION_MAIN);
				startMain.addCategory(Intent.CATEGORY_HOME);
				startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(startMain);
				System.exit(1);
			} else {// android2.1
				ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
				am.restartPackage(getPackageName());
			}
		}
	}
}
